package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.mapper.SuprAuthMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWAJIUAPI;
import com.ruoyi.system.outto.goods.NEWWUYOUAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class NEWAJIUAPIImpl implements NEWAJIUAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,  SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"add",salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.doPostForm(salePartner.getOther()+"/openapi/account/add", params,null);
        log.info("阿酒添加接口请求参数={}", JSONObject.toJSONString(params));
        log.info("阿酒添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        JSONObject jsonObject = JSONObject.parseObject(resultJson.getString("data"));
        if(!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code" , 500);
            } else {
                result.put("code" , 200);
                ArtRec artRecreq = new ArtRec();
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                if(artRecs.size()>0) {
                    artRecs.get(0).setOutid(jsonObject.getString("id"));
                    artRecMapper.updateArtRec(artRecs.get(0));
                }else{
                    artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                    artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                    artRecreq.setType(LCConstant.interAdd);
                    artRecreq.setConfig(salePartner.getId());
                    artRecreq.setSaleCode(salePartner.getSaleName());
                    artRecreq.setOutid(jsonObject.getString("id"));
                    artRecMapper.insertArtRec(artRecreq);
                }
            }
            result.put("msg", resultJson.getString("msg"));
        }else{
            result.put("code" , 500);
            result.put("msg", "添加失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"edit",salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.doPostForm(salePartner.getOther()+"/openapi/account/edit", params,null);
        log.info("阿酒编辑接口请求参数={}", JSONObject.toJSONString(params));
        log.info("阿酒编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if(!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code" , 500);
            } else {
                result.put("code" , 200);
            }
            result.put("msg", resultJson.getString("msg"));
        }else{
            result.put("code" , 500);
            result.put("msg", "编辑失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String type,SalePartner salePartner) {
        GameAttribute gameAttribute = null;
        if(Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF16())){
                throw new GlobalException("实名情况不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
        }else if(Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())){
                throw new GlobalException("实名情况不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("原神")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF20())){
                throw new GlobalException("实名情况不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("英雄联盟")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名情况不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())){
                throw new GlobalException("实名情况不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")){
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())){
                throw new GlobalException("实名情况不能为空");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }
        Map<String, Object> params = new TreeMap<>();
        params.put("mid", salePartner.getTwoOther());
        if(!type.equals("add")){
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            params.put("id", artRecs.get(0).getOutid());
        }
        String daqu = youxiqufu();
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.parseObject(daqu).getString("data"));
        for(Object o : jsonArray){
            if(goodsInfoAndAttrValueDto.getGameName().replace("枪战王者","CF手游").contains(JSONObject.parseObject(o.toString()).getString("game_name"))){
                params.put("game_id",JSONObject.parseObject(o.toString()).getString("game_id"));
                JSONArray jsonArray1 =  JSONArray.parseArray(JSONObject.parseObject(o.toString()).getString("area"));
                if(goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")||goodsInfoAndAttrValueDto.getGameName().contains("和平精英")||goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")||goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")) {
                    for (Object p : jsonArray1) {
                        if (JSONObject.parseObject(p.toString()).getString("area_name").replace("（", "").replace("）", "").contains(goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName())) {
                            params.put("area_id", JSONObject.parseObject(p.toString()).getString("area_id"));
                            break;
                        }
                    }
                }else if(goodsInfoAndAttrValueDto.getGameName().contains("原神")){
                    if(goodsInfoAndAttrValueDto.getGroupName().contains("米哈游")){
                        params.put("area_id", 37);
                    }else{
                        params.put("area_id", 39);
                    }
                }else if(goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
                    JSONArray jsonArray2 =  JSONArray.parseArray(JSONObject.parseObject(o.toString()).getString("area"));
                    for (Object p : jsonArray2) {
                        if(goodsInfoAndAttrValueDto.getGroupName().contains(JSONObject.parseObject(p.toString()).getString("area_name"))){
                            params.put("area_id", JSONObject.parseObject(p.toString()).getString("area_id"));
                        }
                    }
                }
            }
        }
        if(goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")||goodsInfoAndAttrValueDto.getGameName().contains("和平精英")) {
            if(gameAttribute.getFieldName().contains("可二次实名")) {
                params.put("real_name", 1);
            }else if(gameAttribute.getFieldName().contains("已删实名")){
                params.put("real_name", 2);
            }else{
                params.put("real_name", 3);
            }
            if(goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")){
                params.put("hero_num",goodsInfoAndAttrValueDto.getF7()==null||goodsInfoAndAttrValueDto.getF7().equals("")?0:goodsInfoAndAttrValueDto.getF7());
                params.put("skin_num",goodsInfoAndAttrValueDto.getF8()==null||goodsInfoAndAttrValueDto.getF8().equals("")?0:goodsInfoAndAttrValueDto.getF8());
                params.put("camp_id",goodsInfoAndAttrValueDto.getF17()==null||goodsInfoAndAttrValueDto.getF17().equals("")?123456:goodsInfoAndAttrValueDto.getF17());
            }else{
                params.put("hero_num",goodsInfoAndAttrValueDto.getF8()==null||goodsInfoAndAttrValueDto.getF8().equals("")?0:goodsInfoAndAttrValueDto.getF8());
                params.put("skin_num",goodsInfoAndAttrValueDto.getF9()==null||goodsInfoAndAttrValueDto.getF9().equals("")?0:goodsInfoAndAttrValueDto.getF9());
                params.put("camp_id",goodsInfoAndAttrValueDto.getF13()==null||goodsInfoAndAttrValueDto.getF13().equals("")?123456:goodsInfoAndAttrValueDto.getF13());
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("原神")||goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")){
            if(gameAttribute.getFieldName().contains("有修改人脸机会/实名是本人")) {
                params.put("real_name", 1);
            }else if(gameAttribute.getFieldName().contains("已删人脸实名可随时认证")){
                params.put("real_name", 2);
            }else{
                params.put("real_name", 3);
            }
            params.put("hero_num",0);
            params.put("skin_num",0);
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
            if(gameAttribute.getFieldName().contains("有修改机会且实名是本人")) {
                params.put("real_name", 1);
            }else if(gameAttribute.getFieldName().contains("已删实名")){
                params.put("real_name", 2);
            }else{
                params.put("real_name", 3);
            }
            params.put("hero_num",0);
            params.put("skin_num",0);
        }
        params.put("content",goodsInfoAndAttrValueDto.getTitle()==null||goodsInfoAndAttrValueDto.getTitle().equals("")?goodsInfoAndAttrValueDto.getDes():goodsInfoAndAttrValueDto.getTitle());
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(),  salePartner.getSeleep());
        commonApi.setPrice(bigDecimal,goodsInfoAndAttrValueDto.getId(), salePartner);
        params.put("sale_price",bigDecimal);

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String pic = "";
        if (Objects.nonNull(goodsInfoAndAttrValueDto.getTitleImg())){
            pic = goodsInfoAndAttrValueDto.getTitleImg() + ",";
        }
        if (!CollectionUtils.isEmpty(infoImgs)) {
            pic = pic + infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            pic =  pic + LCConstant.defaultImg;
        }
        params.put("img_list", pic);
        params.put("account_num",goodsInfoAndAttrValueDto.getId());
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1) + salePartner.getSaleKey();
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        System.out.println(sign);
        params.put("sign", sign);
        return params;
    }
    private List<GameAttribute> getGameAttributs(String ids) {
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }
    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto ,SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = new TreeMap();
        Map<String, Object> result = new HashMap<>();
        params.put("mid",salePartner.getTwoOther());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        params.put("id",artRecs.get(0).getOutid());
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1) + salePartner.getSaleKey();
        String sign = DigestUtils.md5Hex(cover);
        params.put("sign", sign);
        String response = HttpUtils.doPostForm(salePartner.getOther()+"/openapi/account/del", params,null);
        log.info("阿酒删除接口请求参数={}", JSONObject.toJSONString(params));
        log.info("阿酒删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)){
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                if(artRecs.size()>0) {
                    artRecMapper.deleteArtRecById(artRecs.get(0).getId());
                }
            }
            result.put("msg", resultJson.getString("msg"));
        }else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);

        return AjaxResult.success(result);
    }

    public static void main(String[] args) {

        String response = youxiqufu();

        System.out.println(response);
    }

    public static String youxiqufu(){
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> head = new HashMap<>();
        head.put("Content-Type", "application/x-www-form-urlencoded");
        params.put("mid",6);
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1) + "GSDMF2JD6A55BFJE";
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        System.out.println(sign);
        params.put("sign", sign);
        System.out.println(params);
        String response = HttpUtils.doPostForm("http://www.7560.com/openapi/account/game", params,head);
        return response;
    }

}
